<?php

/**
 * Demo:
 *
 * $content = file_get_contents('https://www.12345.com/shenzhen/co/725588.htm');
 * $dom = (new DomAnalysis)->load($content)->query('//*[@id="gongshang"]/h4');
 * $dom = (new DomAnalysis($content))->query('//*[@id="gongshang"]/div/table/tr[2]/td[2]');
 * var_dump($dom);
 */

class DomAnalysis
{
    public $document;
    public $xp;

    function __construct(string $content = '')
    {
        libxml_use_internal_errors(true);
        libxml_clear_errors();
        $this->document                      = new DOMDocument();
        $this->document->strictErrorChecking = false;
        if (!empty($content)) {
            $this->document->loadHTML(clean_html($content));
            $this->xp = new DOMXPAth($this->document);
        }
    }

    public function load(string $content)
    {
        if (!empty($content)) {
            $this->document->loadHTML(clean_html($content));
            $this->xp = new DOMXPAth($this->document);
        }
        return $this;
    }

    public function query(string $xpath): array
    {
        $dataset  = [];
        $elements = $this->xp->query($xpath);
        if ($elements && $elements->length > 0) {
            for ($i = 0; $i < $elements->length; $i++) {
                $ele = $elements->item($i);
                array_push($dataset, $ele);
            }
        }
        return $dataset;
    }

    function __destruct()
    {
        $this->xp = null;
    }

}
